JavaScript Form Validation

1. What is Form Validation?

Form validation is the process of checking that the data entered by a user into a web form is correct, complete, and secure before it is processed. It is crucial for:

2. Types of Form Validation

There are two main types of validation:

3. HTML5 Built-in Validation

HTML5 provides built-in attributes to validate data without writing any JavaScript.

<input type="text" required>          <!-- Field cannot be empty -->
<input type="email" required>         <!-- Must be an email format -->
<input type="number" min="1" max="10"> <!-- Number between 1 and 10 -->
<input type="text" minlength="3">      <!-- Minimum 3 characters -->
        

4. JavaScript Validation Logic

While HTML5 is great, JavaScript gives you full control over validation rules and custom error messages.

The general logic is:

  1. Listen for the form's submit event.
  2. Prevent the default submission using e.preventDefault().
  3. Check the values of input fields against your rules.
  4. If invalid, show an error message and stop. If valid, proceed.

5. Example: Custom Form Validation

Try submitting the form empty or with invalid data to see the validation in action.

let form = document.getElementById("regForm");

form.addEventListener("submit", function(e) {
    e.preventDefault(); // Stop form submission

    if(validate()) {
        document.getElementById("successMsg").innerText =
        "Form Submitted Successfully!";
    }
});

function validate() {
    let valid = true;

    let name = document.getElementById("name").value;
    let email = document.getElementById("email").value;
    let password = document.getElementById("password").value;

    // Name Validation
    if(name.trim() === "") {
        document.getElementById("nameError").innerText = "Name required";
        valid = false;
    }

    // Email Validation
    if(email.trim() === "") {
        document.getElementById("emailError").innerText = "Email required";
        valid = false;
    }

    // Password Validation
    if(password.length < 6) {
        document.getElementById("passError").innerText =
        "Minimum 6 characters";
        valid = false;
    }

    return valid;
}
        

6. Validation Using Regular Expressions (Regex)

Regular Expressions are patterns used to match character combinations in strings. They are powerful for validating complex formats like emails, phone numbers, or passwords.

// Simple Email Regex Pattern
let emailPattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;

let email = "test@example.com";

// .test() returns true if the string matches the pattern
if(!emailPattern.test(email)) {
    emailError.innerText = "Invalid email format";
}
        
Output will appear here...

7. Comparison: Validation Methods

Validation Type Speed Security Use Case
HTML5 Fast Low Basic forms
JavaScript Fast Medium Custom rules
Server-Side Slow High Final validation
Best Practice: Always use both client-side (for UX) and server-side (for security) validation together. Never rely solely on JavaScript validation as it can be disabled by the user.

Practice Questions

Test your understanding of JavaScript Form Validation.

Easy

Q1: Prevent empty form submission using HTML5.

  • Create a text input field for a username.
  • Use an HTML5 attribute to prevent the form from submitting if the field is empty.
Easy

Q2: Prevent default form submission.

  • Assume you have a form with the ID myForm.
  • Attach an event listener for the submit event.
  • Write the JavaScript method to stop the page from reloading.
Medium

Q3: Validate a numeric input field.

  • Retrieve the value from an input field with the ID age.
  • Convert the value to a Number.
  • Log an error message if the age is less than 18.
Medium

Q4: Validate a password using Regular Expressions (Regex).

  • Write a regex pattern for a password.
  • Ensure it is at least 8 characters long.
  • Ensure it contains at least one number.
  • Test the pattern against the string "pass1234" and log the result.
Hard

Q5: Create a custom email validation script.

  • Retrieve the value of an email input field.
  • Check if it contains the "@" symbol and ends with ".com".
  • If invalid, display an error message in a span with the ID emailError.

Answer

Code: